// https://www.lintcode.com/problem/spiral-array/

public class Solution {
    /**
     * @param n: a Integer
     * @return: a spiral array
     */
    public int[][] spiralArray(int n) {
        // write your code here
        int[][] ret = new int[n][n];
        int start_row = 0, end_row = n;
        int start_col = 0, end_col = n;
        int i = 1;
        while (i <= (n * n)) {
            for (int j = start_col; j < end_col; ++j) { // up edge
                ret[start_row][j] = i;
                ++i;
            }
            for (int j = start_row + 1; j < (end_row - 1); ++j) { // right edge
                ret[j][end_col - 1] = i;
                ++i;
            }
            if ((end_row - 1) > start_row) {
                for (int j = (end_col - 1); j >= start_col; --j) { // bottom edge
                    ret[end_row - 1][j] = i;
                    ++i;
                }
            }
            for (int j = (end_row - 2); j > start_row; --j) { // left edge
                ret[j][start_col] = i;
                ++i;
            }
            ++start_row;
            --end_row;
            ++start_col;
            --end_col;
        }
        return ret;
    }
}